package com.jims.api.v1.controller.weixin.doctor;

import com.jims.master.common.utils.SpringContextHolder;
import com.jims.master.modules.sys.dao.UserDao;
import com.jims.master.modules.sys.dao.WxPublicNoDao;
import com.jims.master.modules.sys.entity.WxPublicNo;
import com.jims.master.modules.sys.service.WxPublicNoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

public class WX_TokenUtil {

    private static WxPublicNoDao wxPublicNoDao = SpringContextHolder.getBean(WxPublicNoDao.class);
    private static Logger log = LoggerFactory.getLogger(WX_TokenUtil.class);
    /*@Resource
    private  WxPublicNoService wxPublicNoService;
    private static WX_TokenUtil wx_tokenUtil;

    @PostConstruct
    public void init(){
        wx_tokenUtil = this;
        wx_tokenUtil.wxPublicNoService = this.wxPublicNoService;
    }*/
    /**
     *  获得微信 AccessToken
     * access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
     * 开发者需要access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取
     * 的access_token失效。
     * （此处我是把token存在Redis里面了）
     */

   /* public static AccessToken getWXToken() {

        String appId="wxdb231ffe0bc215e0";
        String appSecret="3ad771029dade087045c3b86f009a73e";
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId+"&secret="+ appSecret;
        JSONObject jsonObject = WX_HttpsUtil.httpsRequest(tokenUrl, "GET", null);
        System.out.println("jsonObject:"+jsonObject);
        AccessToken access_token = new AccessToken();
        if (null != jsonObject) {
            try {
                access_token.setAccessToken(jsonObject.getString("access_token"));
                access_token.setExpiresin(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                access_token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }

        return access_token;
    }*/


    public static String getAccessToken() {
        //保存access_token文件名字
        WxPublicNo wxPublicNo=wxPublicNoDao.get("b5850ddef3e3477bbe077984be0022b7");
        /*String FileName = "WxTokenUtil.properties";
        try {
            // 从文件中获取token值及时间
            Properties prop = new Properties();// 属性集合对象
            InputStream fis = WX_TokenUtil.class.getClassLoader().getResourceAsStream(FileName);
            prop.load(fis);// 将属性文件流装载到Properties对象中
            fis.close();// 关闭流
            //获取Appid，APPsecret
            String APPID = prop.getProperty("APPID");
            String APPSECRET = prop.getProperty("APPSECRET");
            // 获取accesstoken，初始值为空，第一次调用之后会把值写入文件
            String access_token = prop.getProperty("access_token");
            String expires_in = prop.getProperty("expires_in");
            String last_time = prop.getProperty("last_time");

            int int_expires_in = 0;
            long long_last_time = 0;

            try {
                int_expires_in = Integer.parseInt(expires_in);
                long_last_time = Long.parseLong(last_time);

            } catch (Exception e) {

            }*/
        String APPID = wxPublicNo.getAppId();
        String APPSECRET = wxPublicNo.getAppSecret();
        // 获取accesstoken，初始值为空，第一次调用之后会把值写入文件
        String access_token = wxPublicNo.getAccessToken();
        String expires_in = wxPublicNo.getExpiresIn();
        String last_time = wxPublicNo.getLastTime();
        int int_expires_in = 0;
        long long_last_time = 0;
            //得到当前时间
            long current_time = System.currentTimeMillis();

            // 每次调用，判断expires_in是否过期，如果token时间超时，重新获取，expires_in有效期为7200
            if ((current_time - long_last_time) / 1000 >= int_expires_in) {
                //获取token url
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + APPID + "&secret=" + APPSECRET;
                //发送http请求得到json流
                JSONObject jobject = WX_HttpsUtil.httpsRequest(url, "GET", null);
                System.out.println("返回参数："+jobject.toString());
                //从json流中获取access_token
                String  j_access_token = (String) jobject.get("access_token");
                String  j_expires_in = jobject.get("expires_in").toString();
                //保存access_token
                if (j_access_token != null && j_expires_in != null) {
                    /*prop.setProperty("access_token", j_access_token);
                    prop.setProperty("expires_in", j_expires_in);
                    prop.setProperty("last_time", System.currentTimeMillis() + "");*/
                    wxPublicNo.setAccessToken(j_access_token);
                    wxPublicNo.setExpiresIn(j_expires_in);
                    wxPublicNo.setLastTime(System.currentTimeMillis() + "");
                    wxPublicNoDao.update(wxPublicNo);
                    /*URL url_ = WX_TokenUtil.class.getClassLoader().getResource(FileName);
                    FileOutputStream fos = new FileOutputStream(new File(url_.toURI()));
                    prop.store(fos, null);
                    fos.close();// 关闭流*/
                }
                //如果已经过期返回获取到的access_token
                return j_access_token;
            } else {
                //如果没有过期，返回从文件中读取的access_token
                return access_token;
            }
       /* } catch (Exception e) {
            return null;
        }*/
    }
    /*public static void main(String[] args) {
        AccessToken accessToken= getWXToken();
        log.debug(accessToken.toString());
    }*/
}
